<template>
    <div class="app-container">
        <div>
            <p class="dialogTitle title">当前地震事件:
                <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
                <span v-else>请在地震事件管理中设置当前地震事件</span>
            </p>
        </div>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent"
                    @click="importTemplate('重置单价导入模板.xlsx')">导出模版</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="currentEvent&&multiple" @click="handleDelete">删除</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe row-key="id" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" :reserve-selection="true" width="55" />
            <el-table-column label="序号" align="center" width="55">
                <template #default="scope">
                    <span>{{ (queryParams.page - 1) * queryParams.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="房屋结构类型" align="center" prop="structureType" show-overflow-tooltip>
                <template #default="scope">
                    <el-tooltip class="box-item" effect="dark" :content="scope.row.commentInfo" placement="bottom">
                        <span>{{getStructureType(scope.row.structureType)}}</span>
                    </el-tooltip>
                </template>   
            </el-table-column>
            <el-table-column label="重置单价（元/平米）" align="center" prop="resetPrice" show-overflow-tooltip/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="addRef" label-width="160px" :model="form" :rules="rules">
                <el-row style="margin: 20px 0;">
                    <el-col>
                        <el-form-item label="房屋结构类型" prop="structureType" required>
                            <el-input v-model="form.structureType" placeholeder="请输入房屋结构类型" disabled ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="重置单价（元/平米）" prop="resetPrice">
                            <el-input v-model="form.resetPrice" placeholeder="请输入重置单价（元/平米）" clearable ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="上报人" prop="reporter" required>
                            <el-input v-model="form.reporter" placeholeder="请输入上报人" disabled ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="上报时间" prop="reporterTime" required >
                            <el-input v-model="form.reporterTime" placeholeder="请输入上报时间" disabled ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="save">保 存</el-button>
                    <el-button @click="open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError" :on-success="handleFileSuccess"
                :data="{ 'xsemId': currentEvent.id }" :auto-upload="false" drag>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                            @click="importTemplate('现场人员导入模板.xlsx')">下载模板</el-link> -->
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="resetPrice">
import { getToken, } from "@/utils/auth";
import useEventStore from "@/store/modules/event";
import { getAllList, getDetail, updateData, del } from "@/api/directLossAssess/resetPrice.js"
import { getDict } from "@/api/system/dict";
const currentEvent = computed(() => useEventStore().currentEvent);
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref([]);
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const showSearch = ref(true);
const open = ref(false);
const title = ref();
const option = [{}];
/*** 导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/resetPrice/reportImport"
});
const validatePositiveNumver = (rule, value, callback) => {
    if (/(^[1-9]\d*$)/.test(value)) {
        callback()
    } else if (!value) {
        callback(new Error('重置单价不能为空'))
    } else {
        callback(new Error('请输入正整数'))
    }
};
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
    },
    form: {
    },
    rules: {
        resetPrice: [{ required: true, message: "重置单价不能为空", trigger: "blur",validator: validatePositiveNumver, }],
    }
})
const { queryParams, form, rules } = toRefs(data)

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    console.log(multiple.value,'lalla');
    ids.value = selection.map((item) => item.id);
};

// 导出模版
function importTemplate(name) {
    proxy.downloadTemplate("/template/download", {
        fileName: name
    }, name);
};


/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +  response.data?response.data:response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
};


// 编辑
function handleEdit(row) {
    title.value = '重置单价'
    detail(row.id);
}


// 查看
function detail(id) {
    getDetail({ id: id }).then(res => {
        open.value = true;
        proxy.resetForm("addRef");
        form.value = res.data;
        form.value.structureType = getStructureType(form.value.structureType);
    })
}

// 保存
function save() {
    proxy.$refs["addRef"].validate(valid => {
        if (valid) {
            updateData({ ...form.value, xsemId: currentEvent.value.id }).then(res => {
                proxy.$modal.msgSuccess("保存成功");
                open.value = false;
                getList();
            })
        }
    })

}

/** 删除按钮操作 */
function handleDelete(row) {
    var id = row.id || ids.value;
    console.log(ids.value,'2222');
    proxy.$modal
        .confirm("是否确认删除该信息，请确认是否要删除？",)
        .then(function () {
            return del(id);
        })
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
}

/** 查询数据列表 */
function getList() {
    if (currentEvent.value) {
        loading.value = true;
        getAllList({ ...queryParams.value, xsemId: currentEvent.value.id }).then(response => {
            dataList.value = response.data.rows ? response.data.rows : [];
            total.value = response.data.total;
            loading.value = false;
        });
    } else {
        dataList.value = [];
        total.value = 0;
    }
}

/** 获取字典值 */
async function getDictData() {
await getDict("jglx").then(response => {
	    option.value = response.data;
	});
}
function getStructureType(val){
	var name = ''
	option.value.forEach(item => {
		if(item.dictItemCode == val) {
			name = item.dictItemName
			return
		}
	})
	return name
}
onMounted(() => {
    setTimeout(() => {
        getList();
    }, 200)
})
getDictData();
</script>
  
<style scoped lang="scss">
.title {
    margin: 0 0 20px !important;
}
</style>
  
  